<!-- 采购订单明细控件 -->
<template>
  <a-space direction="vertical" style="width: 100%">
    <div class="content-item">
      <a-space direction="vertical" style="width: 100%">
        <div class="add-td" style="text-align: right">
          <a-button type="primary" @click="addTd" :disabled="props.disabled"
            >添加</a-button
          >
        </div>
        <a-table
          :columns="props.props.columns"
          :data="props.props.data"
          :scroll="scroll"
          :pagination="false"
          stripe
          :bordered="{
            headerCell: true,
          }"
        >
          <template #columns>
            <a-table-column title="物料编码" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.number" /> </template
            ></a-table-column>
            <a-table-column
              title="物料名称"
              :width="100"
              align="center"
              :ellipsis="true"
              :tooltip="{
                position: 'top',
              }"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.name" /> </template
            ></a-table-column>
            <a-table-column
              title="物料规格"
              :width="100"
              align="center"
              :ellipsis="true"
              :tooltip="{
                position: 'top',
              }"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.spec" /> </template
            ></a-table-column>
            <a-table-column title="基本单位" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.basicName" /> </template
            ></a-table-column>
            <a-table-column title="单价" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-group>
                  <a-input-number
                    :min="1"
                    @change="saleMoneyChange(record)"
                    v-model="record.guidePrice"
                    ref="refInput"
                    hide-button
                    :disabled="props.disabled"
                  />
                  <a-select
                    default-value="人民币"
                    @change="saleUnitChange(record)"
                    v-model="record.guidePriceUnit"
                    :options="['人民币', '美元', '港币']"
                    :disabled="props.disabled"
                  />
                </a-input-group> </template
            ></a-table-column>
            <a-table-column title="折扣" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-number
                  :min="0"
                  @change="cgeDiscount(record)"
                  hide-button
                  v-model="record.discount"
                  :disabled="props.disabled"
                >
                  <template #append> % </template>
                </a-input-number>
              </template></a-table-column
            >
            <a-table-column title="采购数量" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-number
                  :min="1"
                  @change="amountChange(record)"
                  placeholder="请输入采购数量"
                  v-model="record.amount"
                  :disabled="props.disabled"
                  hide-button /></template
            ></a-table-column>
            <a-table-column title="合计" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-group>
                  <a-input
                    v-model="record.totalPrice"
                    :disabled="props.disabled"
                  />
                  <a-select
                    default-value="人民币"
                    v-model="record.totalPriceUnit"
                    :disabled="props.disabled"
                    :options="['人民币', '美元', '港币']"
                  />
                </a-input-group>
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="100" align="center"
              ><template #cell="{ rowIndex }">
                <a-space>
                  <a-button
                    type="text"
                    status="danger"
                    :disabled="props.disabled"
                    @click="del(rowIndex)"
                    >删除</a-button
                  >
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
        <div>
          <span>总金额：</span
          ><span>{{
            props.props.totalPrice ? props.props.totalPrice : 0
          }}</span>
        </div>
      </a-space>
    </div>
  </a-space>

  <a-modal
    :width="800"
    v-if="visible"
    v-model:visible="visible"
    :mask-closable="false"
    :unmount-on-close="true"
    @ok="handleOk"
  >
    <template #title> 物料产品选择 </template>
    <div class="container">
      <div class="content">
        <a-space :size="30">
          <div style="display: flex">
            <a-space>
              <div>物料名称：</div>
              <a-input-search
                v-model="searchName"
                placeholder="请输入物料编码"
                search-button
                @search="search"
              />
            </a-space>
          </div>
          <div>
            <a-space>
              <a-button @click="reset" type="outline">
                <template #icon> <icon-sync /> </template>重置</a-button
              >
            </a-space>
          </div>
        </a-space>
      </div>
      <!-- <div class="content">
        <a-space :size="30">
          <div style="display: flex">
            <a-space>
              <div>物料编码：</div>
              <a-input-search
                v-model="numberVal"
                placeholder="请输入物料编码"
                search-button
              />
            </a-space>
          </div>
          <div style="display: flex">
            <a-space>
              <div>物料名称：</div>
              <a-input-search
                v-model="nameVal"
                placeholder="请输入物料名称"
                search-button
              />
            </a-space>
          </div>
          <div>
            <a-space>
              <a-button type="primary" @click="search">
                <template #icon> <icon-search /> </template>搜索</a-button
              >
              <a-button @click="reset">
                <template #icon> <icon-sync /> </template>重置</a-button
              >
            </a-space>
          </div>
        </a-space>
      </div> -->
      <div class="content">
        <tableTurn :table-data="getMaterialData" ref="tableRef" :args="args">
          <a-table-column :width="80" align="center">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            align="center"
            :width="200"
            title="物料编码"
            data-index="number"
            :ellipsis="true"
            :tooltip="{
              position: 'top',
            }"
          >
          </a-table-column>
          <a-table-column
            align="center"
            :width="150"
            title="物料名称"
            data-index="name"
            :ellipsis="true"
            :tooltip="{
              position: 'top',
            }"
          >
          </a-table-column>

          <a-table-column
            align="center"
            :width="150"
            title="规格型号"
            data-index="spec"
            :ellipsis="true"
            :tooltip="{
              position: 'top',
            }"
          >
          </a-table-column>
          <a-table-column
            align="center"
            data-index="basicUnitName"
            :width="100"
            title="基本单位"
          >
          </a-table-column>

          <a-table-column
            align="center"
            data-index="singlePrice"
            :width="100"
            title="指导单价"
          >
          </a-table-column>
        </tableTurn>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted, computed, watchEffect } from 'vue';
  import mitter from '@/utils/mitt';
  import dayjs from 'dayjs';
  import {
    GetMaterialList,
    PostMaterialList,
  } from '@/api/inventory-management/material-management';
  // import { GetSupplierProductList } from '@/api/buy-management/supplier-management/supplier-product-overview/index';
  // import { GetMaterialList } from '@/api/inventory-management/material-management';
  import miiter from '@/utils/mitt';
  import { cloneDeep } from 'lodash';

  const props = withDefaults(
    defineProps<{
      props: { [propName: string]: any };
      name?: string;
      required?: boolean;
      disabled?: boolean;
      values: any;
      regex?: {
        [name: string]: {
          role: any;
          name: any;
        };
      };
    }>(),
    {}
  );

  const emit = defineEmits(['update:values', 'update:props']);
  // let copyProps = computed({
  //   get() {
  //     return { ...props.props, totalPrice: 0 };
  //   },
  //   set(val) {
  //     emit('update:props', val);
  //   },
  // });

  interface ParamsType {
    pageIndex: number;
    pageSize: number;
    number: string;
    clientCompanyName: string;
    status: number[];
    startTime: string;
    endTime: string;
  }
  const demandListParams = reactive<ParamsType>({
    pageIndex: 0,
    pageSize: 10,
    number: '',
    clientCompanyName: '',
    status: [],
    startTime: '',
    endTime: '',
  });

  let tableRef = ref();

  const selectedKeys = ref(); // 新增分类弹出框
  let modalVisible = ref(false);
  let currType = ref(''); // 判断是新增主分类还是子分类
  const currForm = reactive({
    list: {},
  });
  const scroll = {
    x: 2000,
  };

  // 选择器配置
  const args = reactive({
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
  });

  // let numberVal = ref(''); // 物料编码搜索值
  let searchName = ref(''); // 物料编码搜索值
  let supplierId = ref(props.props.supplierId ? props.props.supplierId : 0);
  // 获取物料列表数据
  const getMaterialData = async (pageData?: any) => {
    try {
      let msg = {};
      if (searchName.value) msg.name = searchName.value;
      const res = await GetMaterialList({
        ...pageData,
        ...msg,
      });
      if (props.props.data.length) {
        for (let i = 0; i < props.props.data.length; i += 1) {
          const obj1 = props.props.data[i];
          const matchingObjIndex = res.content.findIndex(
            (obj2: any) => obj2.id === obj1.id
          );
          if (matchingObjIndex !== -1) {
            res.content[matchingObjIndex].disabled = true;
          }
        }
      }
      if (res.content === null) res.content = [];
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const search = () => {
    tableRef.value.loadData();
  };

  const selectData = ref<any>([]); // 选中的数据

  const visible = ref(false);

  const del = (key: any) => {
    props.props.data.splice(key, 1);
    mitter.emit('materialRefresh', props.props.data);
  };

  // 新增或编辑
  const addOrEdit = (type: string, record?: any) => {
    currType.value = type;
    modalVisible.value = true;
  };

  const TotalAmount = ref(0);
  // 修改销售单价价格
  const saleMoneyChange = (record: any) => {
    record.discount = 0;
    if (record.guidePrice !== undefined && record.amount !== undefined)
      record.totalPrice = record.guidePrice * record.amount;
    else record.totalPrice = 0;
  };

  // 修改销售数量
  const amountChange = (record: any) => {
    record.discount = 0;
    if (record.guidePrice !== undefined && record.amount !== undefined)
      record.totalPrice = record.guidePrice * record.amount;
    else record.totalPrice = 0;
    // mitter.emit('materialAmountRefresh', record);
  };

  // 修改销售单价单位
  const saleUnitChange = (record: any) => {
    // 销售单价的单位和合计总价的单位同步
    record.totalPriceUnit = record.guidePriceUnit;
  };

  const cgeDiscount = async (record: any) => {
    if (!record.discount) {
      amountChange(record);
    } else {
      let msg = ref(0);
      msg.value = (100 - record.discount) / 100;
      const newMsg = Number(record.guidePrice * record.amount);
      record.totalPrice *= msg.value;
      // eslint-disable-next-line operator-assignment
      record.totalPrice = newMsg * msg.value;
    }
  };
  let refInput = ref();
  const supplierInfo = ref();

  // 弹出框确认按钮
  const changeSupplierAndData = () => {
    if (supplierInfo.value && props.props.data) {
      console.log('08', supplierInfo.value);
      props.props.data.forEach((item: any) => {
        const product = supplierInfo.value.product.find(
          (p: any) => p.managementId === (item.managementId || item.id)
        );
        if (product) {
          item.guidePrice = product.singlePrice;
          item.guidePriceUnit = product.singleUint;
          item.discount = 0;
          item.supplierId = supplierInfo.value.id;
          item.supplierName = supplierInfo.value.name;
          item.totalPrice = item.amount * item.guidePrice;
        } else {
          item.guidePrice = 0;
          item.guidePriceUnit = '';
          item.discount = 0;
          item.totalPrice = 0;
          item.supplierId = 0;
          item.supplierName = '';
        }
      });
      console.log('09', props.props.data);
    }
  };
  miiter.on('clientRefresh', (val) => {
    supplierInfo.value = val.item;
    changeSupplierAndData();
  });

  const handleOk = () => {
    props.props.data = tableRef.value.selectedList.map(
      (item: any, index: number) => {
        return {
          ...item,
          guidePrice: item.singlePrice,
          guidePriceUnit: '人民币',
          discount: 0,
          totalPrice: 0,
          totalPriceUnit: '人民币',
        };
      }
    );
    refInput.value?.focus();
    changeSupplierAndData();
    mitter.emit('materialRefresh', props.props.data);
  };

  // 新增分类弹出框
  const add = () => {
    modalVisible.value = true;
  };

  const getdata = () => {
    mitter.emit('materialRefresh', props.props.data);
  };

  const getTotalAmount = (data: any) => {
    let price = 0;
    data.forEach((item: any) => {
      price += item.totalPrice;
    });
    props.props.totalPrice = price;
    miiter.emit('getTotalAmount', props.props.totalPrice);
  };

  watchEffect(() => {
    if (props.props.data) {
      getTotalAmount(props.props.data);
    }
  });

  onMounted(() => {
    if (props.props.data !== null) {
      getdata();
      props.props.totalPrice = 0;
      getTotalAmount(props.props.data);
    }
  });

  const addTd = () => {
    // if (!supplierId.value) return;
    visible.value = true;
  };
  const reset = () => {
    searchName.value = '';
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .container {
    margin-bottom: 20px;

    .content {
      padding: 10px;
    }
    .state-item {
      position: relative;
      left: 50%;
      transform: translateX(-50%);
    }
    .state-item-Y {
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(148, 191, 255, 1);
      background-color: rgba(232, 243, 255, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #3d7eff;
    }
    .state-item-N {
      color: #f53f3f;
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(251, 172, 163, 1);
      background-color: rgba(255, 236, 232, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .content-item {
    background: inherit;
    background-color: rgba(255, 255, 255, 1);
    border: 1px solid rgba(153, 153, 153, 0.349);
    border-radius: 4px;
    -moz-box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349019607843137);
    -webkit-box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349019607843137);
    box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349);
    padding: 20px 20px;
  }

  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
  }

  // .space-unit {
  //   background-color: var(--color-bg-2);
  //   border-radius: 4px;
  // }

  // .title-fix {
  //   margin: 0 0 12px 0;
  //   font-size: 14;
  // }
  // :deep(.section-title) {
  //   margin: 0 0 12px 0;
  //   font-size: 14px;
  // }
</style>
